import { _decorator, Component, Sprite, UITransform, Animation, AnimationClip, animation, SpriteFrame } from 'cc';
import { EntityManager } from '../../Base/EntityManager';
import { CONTROLLER_ENUM, DIRECTION_ENUM, DIRECTION_ORDER_ENUM, ENTITY_STATE_ENUM, ENTITY_TYPE_ENUM, EVENT_ENUM, PARAMS_NAME_ENUM } from '../../Enums';
import DataManager from '../../Runtime/DataManager';
import EventManager from '../../Runtime/EventManager';
import ResourceManager from '../../Runtime/ResourceManager';
import { TILE_HEIGHT, TILE_WIDTH } from '../Tile/TileManager';
import { WoodenSkeletonStateMachine } from './WoodenSkeletonStateMachine';
const { ccclass, property } = _decorator;

/**
 * 角色管理中心
 */
@ccclass('WoodenSkeletonManager')
export class WoodenSkeletonManager extends EntityManager {
  async init() {
    this.fsm = this.addComponent(WoodenSkeletonStateMachine)
    // 这个 init 是异步的方法
    await this.fsm.init()
    // 为了确保 fsm 创建完成后再进行状态设置，对上面的 init 末尾进行了 await all 处理
    // this.fsm.setParams(PARAMS_NAME_ENUM.IDLE, true) 数据与ui分离
    super.init({
      x:7,
      y:7,
      direction:DIRECTION_ENUM.TOP,
      state:ENTITY_STATE_ENUM.IDLE,
      type:ENTITY_TYPE_ENUM.PLAYER
    })

    EventManager.Instance.on(EVENT_ENUM.PLAYER_BORN, this.onChangeDirection,this)
    EventManager.Instance.on(EVENT_ENUM.PLAYER_MOVE_END, this.onChangeDirection,this)
    this.onChangeDirection(true)
  }

  onChangeDirection(isInit:boolean = false) {
    if (!DataManager.Instance.player) {
      return
    }
    const {x:playerX, y:playerY} = DataManager.Instance.player

    const disX = Math.abs(this.x - playerX)
    const disY = Math.abs(this.y - playerY)
    if (disX === disY && !isInit) {
      return
    }

    if (playerX >= this.x && playerY < this.y) {
      this.direction = disY > disX ? DIRECTION_ENUM.TOP : DIRECTION_ENUM.RIGHT
    }
    else if (playerX <= this.x && playerY <= this.y) {
      this.direction = disY > disX ? DIRECTION_ENUM.TOP : DIRECTION_ENUM.LEFT
    }
    else if (playerX <= this.x && playerY >= this.y) {
      this.direction = disY > disX ? DIRECTION_ENUM.BOTTOM : DIRECTION_ENUM.LEFT
    }
    else if (playerX >= this.x && playerY >= this.y) {
      this.direction = disY > disX ? DIRECTION_ENUM.BOTTOM : DIRECTION_ENUM.RIGHT
    }
  }
}
